#!/usr/bin/env python
# encoding=utf-8

import requests
from PIL import Image
from io import BytesIO
import pymysql


def getImageSizeByUrl(url):
    # 根据图片url 获取图片对象
    html = requests.get(url, verify=False)
    image = Image.open(BytesIO(html.content))
    return image.size


def updatePicture(data):
    # 根据图片url 获取图片对象
    try:
        html = requests.get(data['url'], verify=False)
        image = Image.open(BytesIO(html.content))
    except:
        return

    sql = "update picture_t_picture set width=%d, height=%d where id = %d;" % (image.size[0], image.size[1], data['id'])

    try:
        cursor.execute(sql)
        mysql_conn.commit()
    except:
        print(sql)


if __name__ == '__main__':
    mysql_conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='msquare', charset='utf8mb4')
    cursor = mysql_conn.cursor(pymysql.cursors.DictCursor)

    sql = "select id, url from picture_t_picture where id > %d" % 90461

    try:
        cursor.execute(sql)
        info = cursor.fetchall()
        counts = len(info)
        print("共：", counts, "数据待更新")
        for i, each in enumerate(info):
            updatePicture(each)
            if i % 10 == 0:
                print("当前进度: %.2f %%" % (i / counts * 100))
    except:
        print(sql)

